﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using Kiiro.Model;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Microsoft.SharePoint;
using System.DirectoryServices;


namespace Kiiro.WebServices
{


    [Serializable]
    public class KiiroSecurityStatusFlags
    {
        public bool UserAlreadyExists = false;
        public bool ADUserDoesNotExist = true;
        public bool ExceptionOccurred = false;
        public string Exception;
        public bool Success = false;
    }

    [Serializable]
    public class KiiroUserSummary
    {
        public int ID=0;
        public string Name = "";
        public string Email = "";
        public bool CanCreateProjects = false;

        public KiiroUserSummary()
        {            
        }


        public KiiroUserSummary(int id, string name, string email, bool canCreateProjects)
        {
            ID = id;
            Name = name;
            Email = email;
            CanCreateProjects = canCreateProjects;
        }
    }


    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://mykiiro.com/security")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class KiiroSecurity : System.Web.Services.WebService
    {
        [WebMethod]
        public KiiroUserSummary[] GetActiveUserList(KiiroSecurityStatusFlags status)
        {            

            Guid siteCollectionId;
            string serverRelativeUrl =  null;
            status = new KiiroSecurityStatusFlags();
            KiiroUserSummary[] userSummaries = null ;
            IList<User> users = null;

            try
            {
                //try and get the site collection ID and relative URL
                SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Host + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);

                //users = UserModel.GetActiveUsers(siteCollectionId, serverRelativeUrl);
                users = UserModel.GetUsersFromSPGroups(siteCollectionId, serverRelativeUrl);
                userSummaries = new KiiroUserSummary[users.Count];
                int index = 0;
                foreach (User user in users)
                {                    
                    userSummaries[index] = new KiiroUserSummary(user.SPUserId, user.FullName, user.Email, user.IsAdministrator | user.ManageProjectsOnly);
                    ++index;
                }

            }
            catch (Exception ex)
            {
                status.ExceptionOccurred = true;
                status.Exception = ex.ToString();
            }

            return userSummaries;
        }


        //[WebMethod]
        //public void AddFormsUser(bool tryMatchingToAD, string adDomain, string firstName, string lastName, string title, string phone, string email, string login, string password, string createdByUserName, KiiroSecurityStatusFlags status)
        //{
            
        //    Guid siteCollectionId;
        //    string serverRelativeUrl =  null;
        //    status = new KiiroSecurityStatusFlags();
        //    bool gotADUser = false;
         
        //    try
        //    {
        //        //try and get the site collection ID and relative URL
        //        SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Host + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);
                
                
        //        //try and get the AD user by email and then name
        //        if (tryMatchingToAD)
        //        {

        //            gotADUser = FindUserInADByEmail(email, adDomain, out firstName, out lastName, out title, out phone);

        //        }
                
              
        //    }
        //    catch(Exception ex)
        //    {
        //        status.ExceptionOccurred = true;
        //        status.Exception = ex.ToString();
        //    }
        //}

        //[WebMethod]
        //public void AddADUser(string domain, string login, string createdByUserName, KiiroSecurityStatusFlags status)
        //{

        //    Guid siteCollectionId;
        //    string serverRelativeUrl = null;
        //    status = new KiiroSecurityStatusFlags();
        //    bool gotADUser = false;
        //    string email;
        //    string firstName;
        //    string lastName;
        //    string title;
        //    string phone;

        //    try
        //    {
        //        //try and get the site collection ID and relative URL
        //        SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Host + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);

        //        if (!GetADUserInfo(domain, login, out email, out firstName, out lastName, out title, out phone))
        //            status.ADUserDoesNotExist = true;


        //    }
        //    catch (Exception ex)
        //    {
        //        status.ExceptionOccurred = true;
        //        status.Exception = ex.ToString();
        //    }
        //}
        //private bool GetADUserInfo(string domain, string login, out string email, out string firstName, out string lastName, out string title, out string phone)
        //{
        //    bool found = false;
        //    firstName = null;
        //    lastName = null;
        //    title = null;
        //    phone = null;
        //    email = null;


        //    DirectoryEntry adRoot = new DirectoryEntry();  //"LDAP://" + domain + "/DC=" + domain);
        //    DirectorySearcher searcher = new DirectorySearcher(adRoot);
        //    searcher.SearchScope = SearchScope.Subtree;
        //    searcher.ReferralChasing = ReferralChasingOption.All;
        //    searcher.PropertiesToLoad.Add("mail");
        //    searcher.Filter = String.Format("(SAMAccountName={0})", login + "@" + domain); ;                       
            
        //    SearchResult result = searcher.FindOne();
        //    DirectoryEntry directoryEntry = result.GetDirectoryEntry(); 

        //    if (result != null)
        //    {
        //        found = true;

        //        firstName = directoryEntry.Properties["givenName"][0].ToString();
        //        lastName = directoryEntry.Properties["sn"][0].ToString();
        //        title = directoryEntry.Properties["title"][0].ToString();
        //        phone = directoryEntry.Properties["telephoneNumber"][0].ToString();
        //        email = directoryEntry.Properties["mail"][0].ToString();
        //    }
        //    return found;
        //}

       
       
    
    }
}
